const reg_mark = /^(.+?)\s/;
const reg_sharp = /^\#/;

function createTree(mdArr) {
  let _htmlPool = {};
  let _lastMark = '';

  mdArr.forEach((mdFragment) => {
    const matched = mdFragment.match(reg_mark);

    if (matched) {
      const mark = matched[1]
      const input = matched['input'];

      if (reg_sharp.test(mark)) {
        const tag = `h${mark.length}`;
        const tagContent = input.replace(reg_mark, '');

        if (_lastMark === mark) {
          _htmlPool[tag].tags = [..._htmlPool[tag].tags, `<${tag}>${tagContent}</${tag}>`]
        } else {
          _lastMark = mark;
          _htmlPool[tag] = {
            type: 'single',
            tags: [`<${tag}>${tagContent}</${tag}>`]
          }
        }
      }
    }
  })

  return _htmlPool
}

function compileHTML(_mdArr) {
  const _htmlPool = createTree(_mdArr)
  let _htmlStr = '';
  let item;

  for (let k in _htmlPool) {
    item = _htmlPool[k];
    if (item.type === 'single') {
      item.tags.forEach((tag) => {
        _htmlStr += tag;
      })
    }
  }

  return _htmlStr
}

module.exports = {
  compileHTML
}